import { Home } from "../pages/Home";
import { Login } from "../pages/Login";
import { Register } from "../pages/Register";
import { UpdatePassword } from "../pages/UpdatePassword";
import { Routes, Route, Navigate } from "react-router-dom";
import { PropsWithChildren } from "react";
import { jwtDecode } from "jwt-decode";

interface Meta {
  isLogin?: boolean;
}

const routes = [
  {
    path: "/",
    meta: {
      isLogin: true,
    },
    element: <Home />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/register",
    element: <Register />,
  },
  {
    path: "/update_password",
    element: <UpdatePassword />,
  },
];

const checkTokenValid = () => {
  const token = localStorage.getItem("token");
  if (!token) return false;
  try {
    const decodeToken = jwtDecode(token);
    const currentTime = Date.now() / 1000; // 转为秒
    return decodeToken.exp! > currentTime;
  } catch (error) {
    console.log("token 解析失败", error);
    return false;
  }
};

const AuthRoute = ({ children, meta }: PropsWithChildren<{ meta?: Meta }>) => {
  if (meta && meta?.isLogin && !checkTokenValid()) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>; // 否则渲染子路由内容
};

function AuthRoutes() {
  return (
    <Routes>
      {routes.map((route) => (
        <Route
          key={route.path}
          path={route.path}
          element={<AuthRoute meta={route.meta}>{route.element}</AuthRoute>}
        />
      ))}
    </Routes>
  );
}

export default AuthRoutes;
